from utils import createXY
import numpy as np
import time
import logging
from sklearn.model_selection import train_test_split
from sklearn.utils import shuffle
import pickle
from tabulate import tabulate
from sklearn.model_selection import train_test_split
from lazypredict.Supervised import LazyClassifier

# 配置日志记录
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')



# 加载和预处理数据
train_file = r'D:\project5_基于集成学习的猫狗识别\data_try' 
dest_file = r'D:\project5_基于集成学习的猫狗识别\dest_file'
X, y = createXY(train_folder=train_file, dest_folder=dest_file)
X, y = shuffle(X, y, random_state=42)  # 随机打乱数据
X = np.array(X).astype('float32')
X = X / np.linalg.norm(X, axis=1, keepdims=True)
logging.info("数据加载和预处理完成。")

# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

logging.info("数据集划分为训练集和测试集。")

# 使用LazyClassifier自动选择和评估各种分类器
clf = LazyClassifier()
result, _ = clf.fit(X_train, X_test, y_train, y_test)
print(result)

# 获取F1分数最高的模型
best_model_name = result['F1 Score'].idxmax()  # 获取F1分数最高行的索引值，即：模型名称
print("\nF1分数最高的模型是: ", best_model_name)

# clf.models 是包含所有训练过的模型 (名称, 模型对象) 键值对的字典
best_model = clf.models[best_model_name]  # 根据模型名称，从模型字典中获取模型对象

result = best_model.predict(X_test)  # 该字典可以直接被拿来进行预测
print(f"用{best_model_name}预测X_test的结果是:\n{result}")

with open('best_model.pkl','wb') as f:
    pickle.dump(best_model,f)







